/**
 * 
 */
package com.jjt.kiki.service;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import com.jjt.kiki.bean.Done;
import com.jjt.kiki.bean.No;
import com.jjt.kiki.dao.DoneDao;
import com.jjt.kiki.dao.NoDao;

/**
 * 待爬取队列
 * @author jjtEatJava
 *
 */
public class Frontier {
	private static final BlockingQueue<No> queueGet = new  LinkedBlockingQueue<No>();
	private  final NoDao noDao= new NoDao();
	private final DoneDao  doneDao= new DoneDao();
	private static final class Single{
		private static Frontier instance = new Frontier();
	}
	private Frontier() {
		
	}
	public static Frontier getInstance() {
		return Single.instance;
	}
	public No take() {
		//扩容
			synchronized (this) {
				if(queueGet.peek()==null) {
					List<No> list = noDao.findTop(100);
					System.out.println("数据库查找成功");
					System.out.println(list.size());
					for(No no : list) {
						queueGet.add(no);
					}
				}
				return queueGet.poll();
			}
	}
	public void put(List<No> ukList) {
		//判断是否存在
		synchronized (this) {
			Iterator<No> i = ukList.iterator();
			for(;i.hasNext();) {
				No no = i.next();
				if(isExists(no.getNoUserUk()))
					i.remove();
			}
			this.noDao.save(ukList);
		}
	}
	/**
	 * jjtEatJava
	 * 2017年5月9日
	 * @param uk
	 * @return
	 */
	private boolean isExists(String uk) {
		int countNo = this.noDao.countByNoUserUk(uk);
		int countDone = this.doneDao.countByNoUserUk(uk);
		if((countNo+countDone)==0)
			return false;
		return true;
	}
	/**
	 * jjtEatJava
	 * 2017年5月9日
	 * @param no
	 */
	public void done(No no) {
		//从未爬取中移除
		noDao.delete(no.getNoId());
		//添加到已经爬取
		synchronized (this) {
			Done done = new Done();
			done.setDoneUserUk(no.getNoUserUk());
			done.setFansCount(no.getFansCount());
			done.setFollowCount(no.getFollowCount());
			done.setPubshareCount(no.getPubshareCount());
			done.setAlumCount(no.getAlumCount());
			doneDao.save(done);
		}
	}
	
	//检测ip有效性
	
}
